<?php

declare(strict_types=1);

namespace app\common\logic;

use app\common\lib\Initialize;
use app\common\model\Config as ModelConfig;

class Config
{
    // +----------------------------------------------------------------------
    // | 初始化配置
    // +----------------------------------------------------------------------

    /**
     * 初始化
     */
    public static function init(array $data)
    {
        foreach ($data as $value) {
            $model = ModelConfig::where('key', $value['key'])->findOrEmpty();
            $model->isEmpty() && $model->save(self::changeValue($value));
        }
    }

    /**
     * 转换配置值
     *
     * @param array $value
     */
    private static function changeValue(array $value): array
    {
        if (!empty($value['img_scene'])) {
            // img_scene 1 URl地址 2 绝对路径 3 相对路径
            $value['value'] = Initialize::image($value['value'], $value['img_scene']);
        }
        return $value;
    }

    // +----------------------------------------------------------------------
    // | 获取系统配置
    // +----------------------------------------------------------------------

    /**
     * 根据配置键获取对应的键值
     *
     * @param string $key 配置键
     */
    public static function getValueBykey(string $key)
    {
        $data = ModelConfig::field('key,value')->where('key', $key)->findOrEmpty();
        $data->isEmpty() && fault('系统配置丢失');
        return $data->value;
    }

    /**
     * 根据多个配置键获取系统配置
     *
     * @param string $keys
     */
    public static function getValueBykeys(array $keys)
    {
        $data = ModelConfig::field('key,value')->whereIn('key', $keys)->select();
        return $data->column('value', 'key');
    }

    /**
     * 根据配置组查询系统配置
     *
     * @param string $type 分组名称
     */
    public static function getValueByType(string $type)
    {
        $data = ModelConfig::field('key,value')->where('type', $type)->select();
        return $data->column('value', 'key');
    }
}
